package controller

import (
	"errors"
	"gforum/model"
	"gforum/service"
	"gforum/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

// comments_controller.go
// 处理 Comment 相关的 handle func

// PostComment 在指定 ID 的 Post 下添加 Comment
func PostComment(ctx *gin.Context) {
	id := ctx.Param("id")

	commentContent := ctx.MustGet("commentContent").(model.Comment)

	postedComment, err := service.PostComment(id, commentContent)
	switch {
	case errors.Is(err, service.ErrRecordNotFound):
		utils.NotFound(ctx, err, "postID or userID not found")
		return
	case err != nil:
		utils.InternalServerError(ctx, err, "Internal error in post comment")
		return
	}

	ctx.JSON(http.StatusOK, postedComment)
}

// EditCommentByID 编辑对应 ID 的 Comment
func EditCommentByID(ctx *gin.Context) {
	id := ctx.Param("id")
	var commentContent model.Comment
	if err := ctx.ShouldBindJSON(&commentContent); err != nil {
		utils.BadRequest(ctx, err, "Invalid comment content or missing field")
		return
	}

	updatedComment, err := service.UpdateComment(id, commentContent)
	switch {
	case errors.Is(err, service.ErrRecordNotFound):
		utils.NotFound(ctx, err, "postID or userID not found")
		return
	case err != nil:
		utils.InternalServerError(ctx, err, "Internal error in update comment")
		return
	}

	ctx.JSON(http.StatusOK, updatedComment)
}

func DelCommentByID(ctx *gin.Context) {
	id := ctx.Param("id")

	err := service.DeleteCommentByID(id)

	switch {
	case errors.Is(err, service.ErrRecordNotFound):
		utils.NotFound(ctx, err, "Comment ID not found")
	case err != nil:
		utils.InternalServerError(ctx, err, "DeleteCommentByID failed")
	default:
		utils.StatusOK(ctx, errors.New(""), "Comment deleted")
	}
}

// GetAllCommentsByPostID 获取指定 ID 的 Post 下的所有 Comment
//
// 请求示例：GET /api/posts/1/comments?page=1&size=7
//
// 请求参数:
//   - page: 页码，默认为 1
//   - size: 每页数量，默认为 7
func GetAllCommentsByPostID(ctx *gin.Context) {
	userID := ctx.Param("id")
	if userID == "" {
		utils.BadRequest(ctx, errors.New("post ID is required"), "Post ID is required")
		return
	}

	var query model.Pagination
	if err := ctx.ShouldBindQuery(&query); err != nil {
		utils.InternalServerError(ctx, err, "Error in bind query")
	}
	query.Default()

	comments, err := service.GetAllCommentsByPostID(userID, query)
	switch {
	case err != nil:
		utils.InternalServerError(ctx, err, "Error in getting comments by id")
		return
	}

	total, err := service.GetTotalSize(userID, &model.Comment{})
	if err != nil {
		utils.InternalServerError(ctx, err, "Error in getting total size")
		return
	}

	totalPages := service.GetTotalPage(query.Size, total)

	ctx.JSON(http.StatusOK, gin.H{
		"page":       query.Page,
		"size":       len(*comments),
		"total":      total,
		"totalPages": totalPages,
		"posts":      comments,
	})
}
